<?php

namespace Cron\Controller;

use Common\Controller\ApiController;
use Think\Log;

class CronController extends ApiController {

    public function _initialize() {
        $token = I('get.token');
        if (empty($token) || $token != C('JWT_KEY')) {
            $this->errorResponse('404', '请求失败，请检查');
        }
    }

    /*
     * 检查vip是否过期
     * 
     */

    public function checkVip() {
        date_default_timezone_set('PRC');
        $userModel = D('User');
        $ids = $userModel->where(['viptime' => ['elt', time()], 'vip' => 2])->limit(0, 1000)->getField('id', TRUE);

        if (!empty($ids)) {
            $userModel->where(['id' => ['in', $ids]])->setField('vip', 1);
            //过期提醒加入消息
            foreach ($ids as $v) {
                $data['title'] = '会员vip到期提醒';
                $data['content'] = '由于您没有在vip截止日期续费，现vip已过期';
                $data['receive_id'] = $v;
                $data['rec_type'] = 3;
                $data['is_top'] = 1;
                $data['create_time'] = time();
                $alldata[] = $data;
            }
            D('Message')->addAll($alldata);
            unset($alldata);
        }

        //需要提醒的过期的会员消息
        $time = date('Y-m-d', time());
        $start_time = strtotime("{$time} +6 day");
        $end_time = strtotime("{$time} +5 day");
        $where['viptime'] =  array('between',array($start_time,$end_time)); 
        $where['vip'] = 2; 
        $exprie5day = $userModel->where($where)->order('viptime asc')->limit(0, 1000)->getField('id', TRUE);
        if (!empty($exprie5day)) {
            foreach ($exprie5day as $v) {
                //过期提醒加入消息
                $data['title'] = '您的vip还有5天过期';
                $data['content'] = '您的vip即将在5天后过期，请及时续费';
                $data['receive_id'] = $v;
                $data['rec_type'] = 3;
                $data['is_top'] = 1;
                $data['create_time'] = time();
                $alldata[] = $data;
                D('Message')->addAll($alldata);
            }
        }

        $to = '747056764@qq.com';
        $title = '定时任务-检查vip到期';
        $this->sendEmail($to, $title, json_encode($ids));
        echo 1;
    }

    /** 清除每日任务* */
    public function cronCleanDayTask() {
//        $logFile = LOG_PATH . 'Cron/' . date('Y-m') . '_cleanDayTask.log';
        $redis = redis();
        $taskdaylog = $redis->sMembers('task_day');
        $redis->del('task_day');
        $data = ['message' => 'cron clean day task success', 'time' => date('Y-m-d H:i:s')];
//        Log::write(json_encode($data), Log::INFO, '', $logFile);

        $to = '747056764@qq.com';
        $title = "每日任务定时清除";
        $content = "今天每日任务清除的数据是：" . json_encode($taskdaylog);
        $result = $this->sendEmail($to, $title, $content);
        if ($result) {
            $this->createdResponse();
        } else {
            $this->errorResponse('10001', '失败');
        }
    }

    /*
     * 新人任务。累计阅读时间60分钟
     * 以2分钟为一章计算，需要阅读30章
     * num 章节数量
     * task_id 19 写死
     * gold 送的金币
     */

    public function totalTime60() {
        $historyModel = D('History');
        $num = 30;
        $task_id = 19;
        $gold = 50;
        $mark = '累计阅读60分钟送书币';
        $sql = "SELECT * FROM (SELECT uid,count(1) as a FROM n_history WHERE uid NOT IN (SELECT user_id FROM n_task_done WHERE task_id = {$task_id}) GROUP BY uid ORDER BY uid ASC) as b WHERE a>={$num} ORDER BY a DESC";
        $history = $historyModel->query($sql);
        if (!empty($history)) {
            $time = time();
            foreach ($history as $k => $v) {
                $data['user_id'] = $v['uid'];
                $data['task_id'] = $task_id;
                $data['time'] = $time;
                $alldata[] = $data;

                $goldlog['user_id'] = $v['uid'];
                $goldlog['mark'] = $mark;
                $goldlog['gold'] = $gold;
                $goldlog['add_time'] = $time;
                $goldlog['type'] = 'send';
                $goldlogs[] = $goldlog;
            }
            $Model = M();
            $Model->startTrans();
            $uids = array_column($history, 'uid');
            $res2 = D('User')->where(['id' => ['in', $uids]])->setInc('gold', $gold); //增加用户赠送金币
            $res1 = D('TaskDone')->addAll($alldata);
            $res3 = D('GoldLog')->addAll($goldlogs); //写入记录
            if (!empty($res1) && !empty($res2) && !empty($res3)) {
                $Model->commit();
            } else {
                $Model->rollback();
            }
            $content = "新人任务累计阅读60分钟：" . json_encode($history);
        } else {
            $content = "新人任务累计阅读60分钟：今天没有数据";
        }

        $to = '747056764@qq.com';
        $title = "新人任务累计阅读60分钟";
        $this->sendEmail($to, $title, $content);
        echo 1;
    }

    /*
     * 每日任务10分钟，30分钟，60分钟送书币
     * 思路：1章2分钟算，分号对应5章，15章，30章节
     * 条件以今天为时间
     * 
     */

    public function readtime() {
        $num1 = 5; //至少五章节才修改数据
        $num2 = 15; //至少五章节才修改数据
        $num3 = 30; //至少五章节才修改数据
        $task_id_10 = 21;   //10分钟
        $task_id_30 = 22;   //30分钟
        $task_id_60 = 23;   //1小时

        $redis = redis();
        $redis_task = $redis->get('n_task');
        if (empty($redis_task)) {
            $task = D('Task')->where(['closed' => 0])->select();
            $strTask = serialize($task);
            $redis->set('n_task', $strTask);
        } else {
            $task = unserialize($redis_task);
        }
        $historyModel = D('History');
        $sql = "SELECT * FROM (SELECT uid,count(1)  a FROM n_history as h left join n_user u on u.id =h.uid  WHERE h.time >=  unix_timestamp(curdate()) and u.vip>0 and u.closed = 0 GROUP BY h.uid ORDER BY h.time DESC ) as b where a>={$num1}";
        $history = $historyModel->query($sql);
        $history = array_column($history, 'a', 'uid');
        $taskDone = D('TaskDone');
        $sql2 = "SELECT * FROM n_task_done WHERE time>= unix_timestamp(curdate()) and task_id in ({$task_id_30},{$task_id_60})";
        $taskdone = $taskDone->query($sql2);

        $hasDone10 = [];
        $hasDone30 = [];
        $hasDone60 = [];
        if (!empty($taskdone)) {
            array_multisort(array_column($taskdone, 'task_id'), SORT_DESC, $taskdone);
            //查出已完成的今日阅读时长任务
            foreach ($taskdone as $vv) {
                switch ($vv['task_id']) {
                    case $task_id_60:
                        if (!empty($history)) {
                            unset($history[$vv['user_id']]);
                        }
                        $hasDone60[] = $vv['user_id'];
                        break;
                    case $task_id_30:
                        $hasDone30[] = $vv['user_id'];
                        break;
                    default:
                        break;
                }
            }
        }
        //1增加用户金币，2写入金币记录，3，写入任务完成表
        if (!empty($history)) {
            foreach ($task as $key => $value) {
                if ($value['id'] == $task_id_30) {
                    $curtask30 = $task[$key];
                } elseif ($value['id'] == $task_id_60) {
                    $curtask60 = $task[$key];
                }
            }

            $time = time();
            foreach ($history as $k => $v) {
                if ($v < $num3 && !in_array($k, $hasDone30)) {
                    $goldlog['mark'] = $curtask30['title'];
                    $goldlog['gold'] = $curtask30['description'];
                    $data['task_id'] = $task_id_30;
                    $user2[] = $k;
                } elseif ($v >= $num3) {
                    $goldlog['mark'] = $curtask60['title'];
                    $goldlog['gold'] = $curtask60['description'];
                    $data['task_id'] = $task_id_60;
                    $user3[] = $k;
                }else{
                   unse($history[$k]); 
                }
                //写入任务完成表里
                $data['user_id'] = $k;
                $data['time'] = $time;
                $alldata[] = $data;

                //写入金币记录表里
                $goldlog['user_id'] = $k;
                $goldlog['add_time'] = $time;
                $goldlog['type'] = 'send';
                $goldlogs[] = $goldlog;
            }
            $Model = M();
            $Model->startTrans();
            if (!empty($user2)) {
                $where['id'] = ['in', $user2];
                $res22 = D('User')->where($where)->setInc('gold', $curtask30['description']);
            }//增加用户赠送金币
            if (!empty($user3)) {
                $where['id'] = ['in', $user3];
                $res23 = D('User')->where($where)->setInc('gold', $curtask60['description']);
            } //增加用户赠送金币
            $res1 = D('TaskDone')->addAll($alldata);
            $res3 = D('GoldLog')->addAll($goldlogs); //写入记录
            if (!empty($res1) && !empty($res3)) {
                $Model->commit();
            } else {
                $Model->rollback();
            }
            $content = '每日任务阅读时长奖励:' . json_encode($history);
        } else {
            $content = "每日任务阅读时长奖励：今天没有数据";
        }

        $to = '747056764@qq.com';
        $title = '每日任务阅读时长奖励';
        $this->sendEmail($to, $title, $content);
        echo 1;
    }

    /*
     * 金币记录不足300提醒
     */

    public function goldNotify() {
        $user = D('User')->field('id,gold,nickname')->where(['gold' => ['elt', 300], 'closed' => 0, 'vip' => 1])->select();
        if (!empty($user)) {
            foreach ($user as $v) {
                $data['title'] = '金币不足提醒';
                $data['content'] = "亲爱的{$v['nickname']}用户，您的书币已不足300哦,请及时充值";
                $data['receive_id'] = $v['id'];
                $data['rec_type'] = 3;
                $data['is_top'] = 1;
                $data['create_time'] = time();
                $alldata[] = $data;
            }
            D('Message')->addAll($alldata);
        }

        $to = '747056764@qq.com';
        $title = '定时任务-金币不足提醒';
        $this->sendEmail($to, $title, json_encode($user));
        echo 1;
    }

}
